<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Blacklist;
use app\common\model\FriendApply;
use app\common\model\User as UserModel;
use app\common\model\Friend as FriendModel;
use think\db\Expression;

class Friend extends Api{
    //protected $noNeedLogin = ['editPwd'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查询好友列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists(){
        $name = request()->post('name');
        $userIds = FriendModel::where('user_id',$this->auth->id)->order('created_at','desc')->column('friend_id');
        $applyCount = FriendApply::where('to_user_id',$this->auth->id)->where('status',0)->count();
        if(empty($userIds)){
            $this->success('请求成功',['list'=>[],'apply_count'=>$applyCount]);
        }
        $exp = new Expression('field(id,'. implode(',',$userIds) .')');
        if(!empty($name)){
            $userList = UserModel::where('id','IN',$userIds)->where('nickname','like','%'. $name .'%')->field('id,nickname,mobile,avatar,level,bio,gender,education')->order($exp)->select();
        }else{
            $userList = UserModel::where('id','IN',$userIds)->field('id,nickname,mobile,avatar,level,bio,gender,education')->order($exp)->select();
        }

        $this->success('请求成功',['list'=>$userList,'apply_count'=>$applyCount]);
    }

    /**
     * 审核好友申请
     * @throws \think\Exception
     */
    public function check(){
        $post = request()->post();
        $validate = new \think\Validate([
            'type'   => 'require|in:1,2',
            'applyId'=> 'require',
        ],[
            'type'   => '参数错误',
            'applyId'=> '参数错误'
        ]);
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }
        $apply = FriendApply::where('id',$post['applyId'])->where('to_user_id',$this->auth->id)->where('status',0)->find();
        if(empty($apply)){
            $this->error('申请不存在!');
        }
        FriendApply::where('id',$post['applyId'])->update(['status'=>$post['type']]);

        if($post['type'] == 1){
            FriendModel::create([
                'user_id'   => $apply['apply_user_id'],
                'friend_id' => $apply['to_user_id']
            ]);
            FriendModel::create([
                'user_id'   => $apply['to_user_id'],
                'friend_id' => $apply['apply_user_id']
            ]);
        }

        $this->success('操作成功');
    }

    /**
     * 获取好友申请列表
     */
    public function getApplyList(){
        $list = FriendApply::with(['applyUser','toUser'])->where('apply_user_id',$this->auth->id)->whereOr('to_user_id',$this->auth->id)->order('created_at','desc')->select();
        $this->success('请求成功',$list);
    }

    /**
     * 提交好友申请
     */
    public function addFriendApply(){
        $toUserId = request()->post('toUserId');
        if(empty($toUserId)){
            $this->error('请选择添加用户');
        }
        if($this->auth->id == $toUserId){
            $this->error('不能添加自己为好友');
        }
        $count = FriendApply::where('apply_user_id',$this->auth->id)->where('to_user_id',$toUserId)->where('status','<>',2)->count();
        if($count > 0){
            $this->error('好友申请已存在');
        }
        $count = FriendApply::where('apply_user_id',$toUserId)->where('to_user_id',$this->auth->id)->where('status','<>',2)->count();
        if($count > 0){
            $this->error('好友申请已存在');
        }
        $result = FriendApply::create([
            'apply_user_id'     => $this->auth->id,
            'to_user_id'        => $toUserId,
        ]);
        if(!$result){
            $this->error('请求发送失败！');
        }
        $this->success('请求发送成功,等待对方同意');
    }

    /**
     * 根据手机号查询用户
     */
    public function queryUserInfo(){
        $mobile = request()->post('mobile');
        if(empty($mobile)){
            $this->error('请输入手机号查询');
        }
        // 为防止后期增加别的查询条件，变成可查询多条 结构体出现变化，所以目前使用唯一手机号查询也是用select
        $info = UserModel::where('mobile',$mobile)->where('status',1)->field('id,nickname,mobile,avatar,level,gender,education')->select();
        $this->success('查询成功',$info);
    }

    /**
     * 删除好友
     * @throws \think\Exception
     */
    public function del(){
        $userId = request()->post('user_id');
        $count = FriendModel::where('user_id',$this->auth->id)->where('friend_id',$userId)->count();
        if($count < 1){
            $this->error('好友不存在');
        }
        FriendModel::where('user_id',$this->auth->id)->where('friend_id',$userId)->delete();
        FriendModel::where('user_id',$userId)->where('friend_id',$this->auth->id)->delete();
        $this->success('删除成功');
    }

    /**
     * 拉黑/取消拉黑
     */
    public function blacklist(){
        $userId = request()->post('user_id');
        $count = Blacklist::where('user_id',$this->auth->id)->where('to_user_id',$userId)->count();
        if($count > 0){
            // 取消拉黑
            Blacklist::where('user_id',$this->auth->id)->where('to_user_id',$userId)->delete();
        }else{
            // 拉黑
            Blacklist::create([
                'user_id'   => $this->auth->id,
                'to_user_id'=> $userId
            ]);
        }
        $this->success('操作成功');
    }
}